class JavaTestGenerator {
    constructor() {
        this.initializeElements();
        this.bindEvents();
        this.loadFromStorage();
    }

    initializeElements() {
        this.classPath = document.getElementById('classPath');
        this.methodCode = document.getElementById('methodCode');
        this.generateBtn = document.getElementById('generateBtn');
        this.emptyState = document.getElementById('emptyState');
        this.loadingState = document.getElementById('loadingState');
        this.resultState = document.getElementById('resultState');
        this.errorState = document.getElementById('errorState');
        this.generatedCode = document.getElementById('generatedCode');
        this.errorMessage = document.getElementById('errorMessage');
        this.downloadBtn = document.getElementById('downloadBtn');
    }

    bindEvents() {
        this.generateBtn.addEventListener('click', (e) => {
            e.preventDefault();
            this.generateTest();
        });

        this.downloadBtn.addEventListener('click', () => {
            this.downloadCode();
        });

        // 保存输入到本地存储
        [this.classPath, this.methodCode].forEach(element => {
            element.addEventListener('input', () => this.saveToStorage());
        });

        // 快捷键支持
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                e.preventDefault();
                this.generateTest();
            }
        });
    }

    loadFromStorage() {
        const saved = localStorage.getItem('javaTestGenerator');
        if (saved) {
            try {
                const data = JSON.parse(saved);
                this.classPath.value = data.classPath || '';
                this.methodCode.value = data.methodCode || '';
            } catch (e) {
                console.error('Failed to load saved data:', e);
            }
        }
    }

    saveToStorage() {
        const data = {
            classPath: this.classPath.value,
            methodCode: this.methodCode.value
        };
        localStorage.setItem('javaTestGenerator', JSON.stringify(data));
    }

    async generateTest() {
        const classPath = this.classPath.value.trim();
        const methodCode = this.methodCode.value.trim();

        if (!classPath || !methodCode) {
            this.showError('请填写类路径和方法代码');
            return;
        }

        this.showLoading();

        try {
            const response = await fetch('/api/generate-test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    class_path: classPath,
                    method_code: methodCode
                })
            });

            const data = await response.json();

            if (response.ok) {
                this.showResult(data.test_code);
            } else {
                this.showError(data.error || '生成测试代码失败');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showError('网络错误，请检查网络连接');
        }
    }

    showLoading() {
        this.hideAllStates();
        this.loadingState.style.display = 'block';
        this.generateBtn.disabled = true;
    }

    showResult(code) {
        this.hideAllStates();
        this.resultState.style.display = 'block';
        this.generatedCode.textContent = code;
        
        // 重新应用语法高亮
        if (window.Prism) {
            window.Prism.highlightElement(this.generatedCode);
        }
        
        this.generateBtn.disabled = false;
    }

    showError(message) {
        this.hideAllStates();
        this.errorState.style.display = 'block';
        this.errorMessage.textContent = message;
        this.generateBtn.disabled = false;
    }

    hideAllStates() {
        if (this.emptyState) this.emptyState.style.display = 'none';
        if (this.loadingState) this.loadingState.style.display = 'none';
        if (this.resultState) this.resultState.style.display = 'none';
        if (this.errorState) this.errorState.style.display = 'none';
    }

    downloadCode() {
        const code = this.generatedCode.textContent;
        if (!code) return;

        const className = this.classPath.value.split('.').pop();
        const fileName = `${className}Test.java`;
        
        const blob = new Blob([code], { type: 'text/java' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new JavaTestGenerator();
});